package com.xwj.server;

import org.apache.zookeeper.*;

import java.io.IOException;

/**
 * @author xwj
 * @date 2020/6/3
 */
public class DistributeServer {
    public static final String connectString = "106.54.221.17:2181,39.106.76.112:2181,111.231.53.97:2181";
    private static int sessionTimeout = 2000;
    private ZooKeeper zk = null;
    private String parentNode = "/servers";

    /**
     * 连接到zk集群
     *
     * @throws IOException
     */
    public void getConnect() throws IOException {
        //        zk = new ZooKeeper(connectString, sessionTimeout, new
//                Watcher() {
//                    @Override
//                    public void process(WatchedEvent event) {
//                    }
//                });
        zk = new ZooKeeper(connectString, sessionTimeout, (event) -> {
//            System.out.println(event.getType());
        });
    }

    /**
     * 注册服务
     *
     * @param hostname
     * @throws Exception
     */
    public void registerServer(String hostname) throws
            Exception {
        String create = zk.create(parentNode + "/server",
                hostname.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.EPHEMERAL_SEQUENTIAL);
        System.out.println(hostname + " is online " + create);
    }

    /**
     * 业务功能
     *
     * @param hostname
     * @throws Exception
     */
    public void business(String hostname) throws Exception {
        System.out.println(hostname + " is working ...");
        Thread.sleep(Long.MAX_VALUE);
    }

    public static void main(String[] args) throws Exception {
        // 1 获取 zk 连接
        DistributeServer server = new DistributeServer();
        server.getConnect();
        // 2 利用 zk 连接注册服务器信息
        server.registerServer("xwj.com");
        // 3 启动业务功能
        server.business("xwj.com");
    }
}
